
#ifndef __THREADPOOL_H
#define __THREADPOOL_H

#include "CWorkerThread.h"
#include "CThreadMutex.h"
#include "CCondition.h"

#include <vector>
#include <algorithm>
using namespace std;

class CWorkerThread;

class CThreadPool
{
private:
  unsigned int  m_iMaxNum;
  unsigned int  m_iAvailLow;
  unsigned int  m_iAvailHigh;
  //unsigned int  m_iAvailNum;
  unsigned int  m_iInitNum;
  
public:
  CWorkerThread *GetIdleThread();
  void AppendToIdleList(CWorkerThread* jobthread);
  void MoveToBusyList(CWorkerThread* idlethread);
  void MoveToIdleList(CWorkerThread* busythread);
  
  void DeleteIdleThread(int num);
  void CreateIdleThread(int num);

public:
  CThreadMutex  m_BusyMutex;
  CThreadMutex  m_IdleMutex;

  vector<CWorkerThread*>  m_ThreadList;
  vector<CWorkerThread*>  m_BusyList;
  vector<CWorkerThread*>  m_IdleList;
  
  CThreadPool();
  CThreadPool(int iMaxNum, int iAvailLow, int iAvailHigh, int iInitNum);
  ~CThreadPool();
  
  void SetMaxNum(int maxnum){m_iMaxNum = maxnum;}
  int GetMaxNum(){return m_iMaxNum;}
  void SetAvailLowNum(int minnum){m_iAvailLow = minnum;}
  int GetAvailLowNum(){return m_iAvailLow;}
  void SetAvailHighNum(int highnum){m_iAvailHigh = highnum;}
  int GetAvailHighNum(){return m_iAvailHigh;}
  //int GetActualAvailNum(){return m_iAvailNum;}
  int GetAllNum(){return m_ThreadList.size();}
  int GetIdlNum(){return m_IdleList.size();}
  int GetBusyNum(){return m_BusyList.size();}
  void SetInitNum(int initnum){m_iInitNum = initnum;}
  int GetInitNum(){return m_iInitNum;}
  
  void TerminateAll();
  int Run(CJob* job, void* jobdata); 
};
#endif